import axios from 'axios';
import { useJWTStore } from '../stores/JWT'; // 导入JWT Store

const baseURL = 'http://localhost:5000';
// const baseURL = 'https://chat.scholarhero.cn/api';

const axiosInstance = axios.create({
  baseURL,
  timeout: 5000,
});

const api = {

  completion: async (inputText, history, onProgressCallback) => {
    console.log('completion', inputText, history);
    try {
      const source = axios.CancelToken.source();
  
      const response = await axiosInstance.post(
        '/chat/completion',
        {
          input_text: inputText,
          history: history,
        },
        {
          responseType: 'text',
          onDownloadProgress: (progressEvent) => {
            const text = progressEvent.currentTarget.response;
            onProgressCallback(text);
          },
          cancelToken: source.token,
        }
      );
  
      return response.data;
    } catch (error) {
      if (axios.isCancel(error)) {
        console.log('Request canceled:', error.message);
      } else {
        console.error('Request error:', error);
        throw error;
      }
    }
  },
  login: async (username, password) => {
    const jwtStore = useJWTStore();
    try {
      const response = await axiosInstance.post('/account/login', { username, password });
      jwtStore.updateToken(response.data.token); // 更新JWT Token
      jwtStore.updateRole(response.data.role); // 更新JWT Role
      console.log("token",response.data.token)
      return response;
    } catch (error) {
      return Promise.reject(error);
    }
  },

  getUserInfo: async () => {
    const jwtStore = useJWTStore();
    const token = jwtStore.getToken;
    // console.log("token",token);
    try {
      return await axiosInstance.get('/account/info', { headers: { 'Authorization': `Bearer ${token}` } });
    } catch (error) {
      return Promise.reject(error);
    }
  },
  
  getCourseList: async (category)  => {
    try {
      const jwtStore = useJWTStore();
      const token = jwtStore.getToken;
      
      return await axiosInstance.get('/course/list-query', {
        headers: { 
          'Authorization': `Bearer ${token}`,
         },
        params: { "category": category }
      });
    } catch (error) {
      console.log(error);
      return Promise.reject(error);
    }
  },

  createCourse: async (courseData) => {
    try {
      const jwtStore = useJWTStore();
      const token = jwtStore.getToken;
  
      console.log(token);
  
      return await axiosInstance.post(
        '/course/create',
        {
          "course_name": courseData.course_name,
          "course_number": courseData.course_number,
          "course_description": courseData.course_description,
          "course_class": courseData.course_class,
          "student_list": courseData.student_list,
        },
        {
          headers: { 'Authorization': `Bearer ${token}` }
        }
      );
    } catch (error) {
      return Promise.reject(error);
    }
  },

  getCourseInfo: async (courseNum)  => {
    try {
      const jwtStore = useJWTStore();
      const token = jwtStore.getToken;
      
      return await axiosInstance.get('/course/manage/info', {
        headers: { 'Authorization': `Bearer ${token}` },      
        params: { "course_number": courseNum }
      });
    } catch (error) {
      return Promise.reject(error);
    }
  },

  getStudentsByCourseId: async (courseNum)  => {
    try {
      const jwtStore = useJWTStore();
      const token = jwtStore.getToken;
      
      return await axiosInstance.get('/course/manage/student', {
        headers: { 'Authorization': `Bearer ${token}` },      
        params: { "course_number": courseNum }
      });
    } catch (error) {
      return Promise.reject(error);
    }
  },

  getKnowledgeBaseFiles: async (courseNum)  => {
    try {
      const jwtStore = useJWTStore();
      const token = jwtStore.getToken;
      
      return await axiosInstance.get('/course/manage/knowledge-base', {
        headers: { 'Authorization': `Bearer ${token}` },      
        params: { "course_number": courseNum }
      });
    } catch (error) {
      return Promise.reject(error);
    }
  },

  getCourseAgentInfo: async (courseNum)  => {
    try {
      const jwtStore = useJWTStore();
      const token = jwtStore.getToken;
      
      return await axiosInstance.get('/course/manage/agent', {
        headers: { 'Authorization': `Bearer ${token}` },      
        params: { "course_number": courseNum }
      });
    } catch (error) {
      return Promise.reject(error);
    }
  },

  updateCourseInfo: async (courseData)  => {
    try {
      const jwtStore = useJWTStore();
      const token = jwtStore.getToken;
      
      return await axiosInstance.post(
        '/course/manage', 
        {
          "course_name": courseData.CourseName,
          "course_number": courseData.CourseNumber,
          "course_description": courseData.CourseDescription,
          "course_class": courseData.Category[0],
          "course_number": courseData.stuNumber,
        },
        {
          headers: { 'Authorization': `Bearer ${token}` }
        }
      );
    } catch (error) {
      return Promise.reject(error);
    }
  },



  updateCourseInfo: (courseData) => axiosInstance.put('/course/manage', courseData),

  deleteCourse: (courseId) => axiosInstance.delete('/course/manage', { body: { course_id: courseId } }),

  // getStudentsByCourseId: (courseId) => axiosInstance.get('/course/manage/student', { body: { course_id: courseId } }),

  manageCourseStudents: (courseId, studentsData) => axiosInstance.post('/course/manage/student', { course_id: courseId, students: studentsData }),

  // getKnowledgeBaseFiles: (courseId) => axiosInstance.get('/course/manage/knowledge-base', { body: { course_id: courseId } }),

  addKnowledgeBaseFile: (fileData) => axiosInstance.post('/course/manage/knowledge-base', fileData),

  // getCourseAgentInfo: (courseId) => axiosInstance.get('/course/manage/agent', { body: { course_id: courseId } }),

  updateCourseAgentSettings: (agentData) => axiosInstance.post('/course/manage/agent', agentData),

  getChatListByCourseId: (courseId) => axiosInstance.get('/chat/release/list', { body: { course_id: courseId } }),

  getChatHistory: (chatId) => axiosInstance.get('/chat/release/history', { body: { chat_id: chatId }}),
};

export default api;